package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.Supplier;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SupplierService;
import com.ktjiaoyu.service.UploadService;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("main/supplier")
public class SupplierController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(SupplierController.class);
    @Resource
    private SupplierService supplierService;

    @Resource
    @Qualifier("toLocalUploadServiceImpl")
    private UploadService uploadService;

    @GetMapping("/page")
    public String page(Model model,
                       @RequestParam(value = "pageNo", defaultValue = "1")Integer pageNo,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){
        Page<com.ktjiaoyu.entity.Supplier> page=null;
        try{
            page=supplierService.findPage(pageNo,pageSize);
            model.addAttribute("pageInfo",page);
        }catch (Exception e){
            logger.error("执行SupplierController.page(Model,Supplier,Integer,Integer)方法出现异常.", e);
            throw new RuntimeException(e);
        }
        return "supplier/page";
    }

    @GetMapping("/save")
    public String save(Model model) {
        List<Supplier> roleList=null;
        try{
            model.addAttribute("roleList",roleList);
            //回显数据时需要 sysUser,这里给个空对象避免出错
            model.addAttribute("supplier",new Supplier());
        }catch (Exception e){
            logger.error("执行UserController.save(Model)方法出现异常.", e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }

    @PostMapping("/save")
    public String deSave(Supplier supplier,
                         @RequestParam(value = "idPic", required = false) MultipartFile idPic) {
        String[] allowImageExt = {"jpg", "png", "jpeg", "gif", "bmp"};
        try {
            // 处理文件上传
            if (idPic != null && !idPic.isEmpty()) {
                String idPicPath = uploadService.uploadFile(idPic, allowImageExt);
                supplier.setBizPicPath(idPicPath);
            }

            // 获取当前登录用户（正确的SysUser类型）
            SysUser loginUser = (SysUser) session(Constants.SESSION_USER);

            // 设置创建者/修改者信息
            if (supplier.getId() == null) {
                // 新增供应商
                supplier.setCreatedUserId(loginUser.getId());
                supplier.setCreatedTime(new Date());  // 添加创建时间
            } else {
                // 修改供应商
                supplier.setUpdatedUserId(loginUser.getId());
                supplier.setUpdatedTime(new Date());  // 添加修改时间
            }

            // 保存数据
            boolean ok = supplierService.saveOrUpdate(supplier);
            if (ok) {
                return redirect("/main/supplier/page");
            }
        } catch (Exception e) {
            logger.error("保存供应商失败，供应商数据：{}", supplier, e);
            throw new RuntimeException("保存供应商信息失败，请稍后再试");
        }
        return "supplier/save";
    }
    @GetMapping("view/{id}")
    public String view(@PathVariable("id")Long id,Model  model){
        Supplier  supplier=null;
        try{
            supplier=supplierService.findBuId(id);
        } catch (Exception e) {
            logger.error("执行UserController.view(@PathVariable(\"id\")Long id,Model  model)方法出现异常.", e);
            throw new RuntimeException(e);
        }
        return "supplier/view";
    }
    @GetMapping("/edit")
    public String toEit(@RequestParam("id")Long id,Model model){
        Supplier supplier=null;
        try{
            supplier=supplierService.findBuId(id);
            //会显示数据时需要 supplier 这里给个空对象避免出错
            model.addAttribute("supplier",supplier);
        } catch (Exception e) {
            logger.error("执行UserController.toEit(@RequestParam(\"id\")Long id,Model model)方法出现异常.", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }
}
